#include "stdafx.h"
#include <ccpl.h>
#include <list.h>
#include <map.h>
#include <string.h>

void reset_ppout( ppoutput *out )
{
    out->comments = lt_create();
    out->tokens = lt_create();
    out->errors = NULL;
    out->ppcond = lt_create();
    out->symbols = sm_create();
    out->types = sm_create();
}

void release_ppout( ppoutput *out )
{
    int i;
    for( i = 0; i < lt_size( out->tokens ); ++i )
        token_release( (token *)lt_get( out->tokens, i ) );
    for( i = 0; i < lt_size( out->comments ); ++i )
        token_release( (token *)lt_get( out->comments, i ) );
    for( i = 0; i < lt_size( out->ppcond ); ++i )
        exp_tree_release( (exp_tree *)lt_get( out->ppcond, i ) );
    sm_for_each( out->symbols, (void(*)(void*))sym_release );
    sm_for_each( out->types, (void(*)(void*))vt_release );
    lt_destroy( out->tokens );
    lt_destroy( out->comments );
    lt_destroy( out->ppcond );
    sm_destroy( out->symbols );
    sm_destroy( out->types );
}

void show_sym( void *s )
{
    symbol *sym = (symbol *)s;
    printf( "%s\n", sym_name( sym, 1 ) );
}

int tpp()
{
    token *tk;
    code cd;
    ppoutput out;
    static char buf[102400000];
    int len;
    char *file = "test.c";
    char cmd[32] = "";
    memset( &out, 0, sizeof(out) );
    while( 1 )
    {
        printf( "ccpl>>" );
        scanf( "%s", cmd );
        if( 0 == strcmp( cmd, "exit" ) )
            break;
        else if( 0 == strcmp( cmd, "pp" ) )
        {
            len = 0;
            printf( "type your code(@end):\n" );
            while( (buf[len] = getchar()) != '@' )
                ++len;
            buf[len] = 0;
            cd.code_buf = (uint8*)buf;
            cd.file = file;
            cd.line = 0;
            reset_ppout( &out );
            preprocess( &cd, &out );

            int i;
            for( i = 0; i < lt_size( out.tokens ); ++i )
            {
                tk = (token *)lt_get( out.tokens, i );
                printf( "%s:%d\n", tk->name, tk->type );
            }
            printf( "token count: %d\n", lt_size( out.tokens ) );
            sm_for_each( out.symbols, show_sym );
            release_ppout( &out );
        }
    }
    return 0;
}
